<template lang="pug">
.page
  .area-manage
    .search-form.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 10 }" :lg="{ span: 10 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w100 参保地区：
          Cascader(v-model="areaName" placeholder="请选择参保地区" change-on-select :data="ProvinceArr" :load-data="loadDataCity" style="width:100%;" filterable)
        Col.pr-20.mb-15(:md="{ span: 14 }" :lg="{ span: 14 }" :xl="{ span: 10 }" :xxl="{span: 8}")
          span.label-txt.w100 公积金方案：
          Input(v-model="planName" placeholder="请输入" clearable)
          Button.ml-10(v-if="hasFind" type="info" @click="searchBtn") 查询
    .odd-manage.pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="thead" :data="planListData" @on-selection-change="tableSelectChange")
        .clearfix.font-16(slot="header")
          .table-title-lefttxt.pull-left
            |合计
            span.text-info.pl-5.pr-5.font-weight {{planTotal}}
            |条
          .pull-right.table-title-btns
            Button.mr-15(v-if="hasCreate" type="info" @click="addFn") 新增
            Button.mr-15(v-if="hasImport" type="info" @click="importBtn") 批量导入
            Button(v-if="hasExport" type="info" @click="exportBtn") 导出
            //- Button(v-if="hasDelete" type="warning" @click="cancelFn") 删除
        template(slot-scope="{ row, index }" slot="operation")
          Button.mr-5(v-if="hasView" type="text" size="small" @click="checkInfoFn(row.id)") 查看
          Button(v-if="hasEdit" type="text" size="small" @click="getReviseAfInfo(row.id)") 修改
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="planTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    include ./modal/add.pug
    include ./modal/check.pug
    BatchImportModal(ref="BatchImportModal" :securityType="securityType" @query="searchBtn" @handleMaxSizeTen="handleMaxSizeTen")

</template>

<script>
// import areaData from '@/libs/areaData.min.js'
import systemApi from '@/api/system.js'
import dataApi from '@/api/data.js'
import BatchImportModal from './modal/BatchImportModal.vue'

export default {
  name: 'AccumulationfundManage',
  components: {
    BatchImportModal
  },
  data () {
    return {
      cascaderShow: false,
      // 弹窗加载状态
      spinShow: false,
      // 参保类型（1社会保险、2公积金）
      securityType: 2,
      // 地区数组
      areaArr: [],
      // 省份数组
      ProvinceArr: [],
      // 查询-参保地区
      areaName: [],
      // 查询-参保方案
      planName: '',
      // 方案列表
      planListData: [],
      // 方案总数
      planTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      loading: false,
      // 查看详情id
      detail_id: '',
      // 选择的id集合
      idList: [],
      // 收费精度下拉
      precisionSelect: [],
      // 大病医疗收费方式
      securityPaymentType: null,
      // 计算方式下拉
      countType: null,
      // 生效时间下拉
      effectiveTime: null,
      // 查看-参保地区
      dt_area_name: [],
      // 新增-参保地区
      add_area_name: [],
      // 新增弹窗
      addModalShow: false,
      // 查看修改弹窗
      checkModalShow: false,
      // 查看和修改弹窗的title
      checkModalTitle: '公积金方案查看',
      // 是否处于查看状态
      isCheckModel: false,
      // 方案详情，点击查看和修改时获取
      codeDetailInfo: {},
      // 新增时获取的提交信息集合
      addDetailInfo: {},
      // 起止时间
      endTime: [{ value: 1, label: '1号' }, { value: 2, label: '2号' }, { value: 3, label: '3号' }, { value: 4, label: '4号' }, { value: 5, label: '5号' }, { value: 6, label: '6号' }, { value: 7, label: '7号' }, { value: 8, label: '8号' }, { value: 9, label: '9号' }, { value: 10, label: '10号' }, { value: 11, label: '11号' }, { value: 12, label: '12号' }, { value: 13, label: '13号' }, { value: 14, label: '14号' }, { value: 15, label: '15号' }, { value: 16, label: '16号' }, { value: 17, label: '17号' }, { value: 18, label: '18号' }, { value: 19, label: '19号' }, { value: 20, label: '20号' }, { value: 21, label: '21号' }, { value: 22, label: '22号' }, { value: 23, label: '23号' }, { value: 24, label: '24号' }, { value: 25, label: '25号' }, { value: 26, label: '26号' }, { value: 27, label: '27号' }, { value: 28, label: '28号' }, { value: 29, label: '29号' }, { value: 30, label: '30号' }, { value: 31, label: '31号' }],
      // 表头
      thead: [
        {
          type: 'selection',
          align: 'center',
          fixed: 'left',
          width: 60
        },
        {
          title: '参保地区',
          align: 'center',
          key: 'areaName',
          minWidth: 90
        },
        {
          title: '公积金方案',
          align: 'center',
          minWidth: 150,
          tooltip: true,
          key: 'planName'
        },
        {
          title: '默认基数（单位）',
          align: 'center',
          key: 'c_baseAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].company.baseAmount
            return h('span', text)
          }
        },
        {
          title: '默认基数（个人）',
          align: 'center',
          key: 'e_baseAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].employee.baseAmount
            return h('span', text)
          }
        },
        {
          title: '最低基数（单位）',
          align: 'center',
          key: 'c_minAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].company.minAmount
            return h('span', text)
          }
        },
        {
          title: '最低基数（个人）',
          align: 'center',
          key: 'e_minAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].employee.minAmount
            return h('span', text)
          }
        },
        {
          title: '最高基数（单位）',
          align: 'center',
          key: 'c_maxAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].company.maxAmount
            return h('span', text)
          }
        },
        {
          title: '最高基数（个人）',
          align: 'center',
          key: 'e_maxAmount',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].employee.maxAmount
            return h('span', text)
          }
        },
        {
          title: '缴纳比例(%)（单位）',
          align: 'center',
          key: 'c_percent',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].company.percent
            return h('span', text)
          }
        },
        {
          title: '缴纳比例(%)（个人）',
          align: 'center',
          key: 'e_percent',
          minWidth: 90,
          render: (h, params) => {
            let row = params.row
            let text = row.details[0].employee.percent
            return h('span', text)
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 140,
          slot: 'operation'
        }
      ],
      // 区域选择的值
      areaValue: '',
      labelData: ['单位部分', '个人部分'],
      countTypeValue: '',
      // 增员生效时间值
      addEffectiveValue: '',
      // 减员生效时间值
      reduceEffectiveValue: '',
      monthShow: false,
      month: [{ value: '1月', label: '1月' }, { value: '2月', label: '2月' }, { value: '3月', label: '3月' }, { value: '4月', label: '4月' }, { value: '5月', label: '5月' }, { value: '6月', label: '6月' }, { value: '7月', label: '7月' }, { value: '8月', label: '8月' }, { value: '9月', label: '9月' }, { value: '10月', label: '10月' }, { value: '11月', label: '11月' }, { value: '12月', label: '12月' }]
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 查看
    hasView () {
      return this.actionArr.indexOf('View') > -1
    },
    // 新增
    hasCreate () {
      return this.actionArr.indexOf('Create') > -1
    },
     // 导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
     // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    hasEdit () {
      return this.actionArr.indexOf('Edit') > -1
    },
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    }
  },
  mounted () {
    this.getPlanList()
    this.getProvince()
    this.getEnum()
    this.areaArr = JSON.parse(localStorage.getItem('areaTree'))
  },
  methods: {
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },
    importBtn () {
      this.$refs.BatchImportModal.openModal()
    },
    // 导出按钮
    exportBtn () {
      systemApi.exportData({
        idList: this.idList,
        areaGUID: this.areaName[this.areaName.length - 1],
        SecurityType: this.securityType,
        PlanName: this.planName,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          let objectUrl = '/' + res.data.data.replace(/\\/g, '\/')
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    /**
     * 分页页码变动
     */
    onpageSizeChange (val) {
      this.PageIndex = 1
      this.PageSize = val
      this.getPlanList()
    },
    // 获取全部省份
    getProvince () {
      dataApi.getProvince().then(res => {
        this.ProvinceArr = res.data.data.map(item => {
          return {
            ...item,
            label: item.name,
            value: item.id,
            children: [],
            loading: false
          }
        })
      })
    },
    /**
     * 分级查询地区
     */
    loadDataCity (val, callback) {
      val.loading = true
      if (val.levelID === 2) {
        dataApi.getCity({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.id,
              children: [],
              loading: false
            }
          })
          val.loading = false
          callback()
        })
      } else {
        dataApi.getArea({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return { ...item, label: item.name, value: item.id }
          })
          val.loading = false
          callback()
        })
      }
    },
    // 获取公积金方案列表
    async getPlanList () {
      this.loading = true
      let res = await systemApi.getPlanList({
        areaGUID: this.areaName[this.areaName.length - 1],
        SecurityType: this.securityType,
        PlanName: this.planName,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      })
      this.idList = []
      this.planListData = res.data.data
      this.planTotal = res.data.totalRows
      this.loading = false
    },
    // 删除方案
    async deletePlan () {
      let res = await systemApi.deletePlan({
        id: this.idList.join(',')
      })
      if (res.data.success) {
        this.$Message.success('删除成功！！')
        this.idList = []
        this.getPlanList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    // 获取下拉
    async getEnum () {
      let groupNames = 'common.precision,common.securitypaymenttype,common.reduceeffecttype,common.totaltype,common.changeoperateduration'
      let res = await dataApi.getEnum({
        groupName: groupNames
      })
      this.precisionSelect = this.getItems(res.data, 'common.precision')
      this.securityPaymentType = this.getItems(res.data, 'common.securitypaymenttype')
      this.countType = this.getItems(res.data, 'common.totaltype')
      this.effectiveTime = this.getItems(res.data, 'common.reduceeffecttype')
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },
    // 获取查看时的详情信息
    async getPlanDetail () {
      this.spinShow = true
      let res = await systemApi.getPlanDetail({
        id: this.detail_id
      })
      this.spinShow = false
      this.codeDetailInfo = res.data.data
      this.codeDetailInfo.details[0].precision = this.codeDetailInfo.details[0].company.precision ? this.codeDetailInfo.details[0].company.precision : this.codeDetailInfo.details[0].employee.precision
      this.dt_area_name = [this.codeDetailInfo.provinceGUID, this.codeDetailInfo.cityGUID, this.codeDetailInfo.areaGUID]
      this.$nextTick(() => {
        this.cascaderShow = true
      })
    },
    // 获取新增时的信息
    async getAddModalInfo () {
      this.spinShow = true
      this.isCheckModel = false
      let res = await systemApi.addModalInfo({
        type: this.securityType
      })
      this.spinShow = false
      this.addDetailInfo = res.data.data
      this.addDetailInfo.details[0].precision = this.addDetailInfo.details[0].company.precision ? this.addDetailInfo.details[0].company.precision : this.addDetailInfo.details[0].employee.precision
    },
    // 保存修改
    async saveRevise () {
      console.log(this.dt_area_name[this.dt_area_name.length - 1])
      this.codeDetailInfo.details[0].company.precision = this.codeDetailInfo.details[0].precision
      this.codeDetailInfo.details[0].employee.precision = this.codeDetailInfo.details[0].precision
      let res = await systemApi.saveRevisePlan({
        Id: this.codeDetailInfo.id,
        AreaGUID: this.dt_area_name[this.dt_area_name.length - 1],
        // PlanName: this.codeDetailInfo.planName,
        SecurityType: this.securityType,
        PayBackMaxMonth: this.codeDetailInfo.payBackMaxMonth,
        ReduceEffectType: this.codeDetailInfo.reduceEffectType,
        IncreasDay: this.codeDetailInfo.increasDay,
        ReduceDay: this.codeDetailInfo.reduceDay,
        TotalType: this.codeDetailInfo.totalType,
        ChangeOperateDuration: this.codeDetailInfo.changeOperateDuration,
        // SeriousIllnessPayment:this.codeDetailInfo.seriousIllnessPayment,
        Details: this.codeDetailInfo.details
      })
      if (res.data.success) {
        this.$Message.success('修改成功！')
        this.isCheckModel = true
        this.checkModalTitle = '公积金参数查看'
        this.getPlanList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    // 确定新增
    async addSave () {
      this.addDetailInfo.details[0].company.precision = this.addDetailInfo.details[0].precision
      this.addDetailInfo.details[0].employee.precision = this.addDetailInfo.details[0].precision
      let res = await systemApi.saveRevisePlan({
        Id: this.addDetailInfo.id,
        AreaGUID: this.add_area_name[this.add_area_name.length - 1],
        // PlanName: this.addDetailInfo.planName,
        SecurityType: this.securityType,
        PayBackMaxMonth: this.addDetailInfo.payBackMaxMonth,
        ReduceEffectType: this.addDetailInfo.reduceEffectType,
        IncreasDay: this.addDetailInfo.increasDay,
        ReduceDay: this.addDetailInfo.reduceDay,
        TotalType: this.addDetailInfo.totalType,
        ChangeOperateDuration: this.addDetailInfo.changeOperateDuration,
        // SeriousIllnessPayment:this.addDetailInfo.seriousIllnessPayment,
        Details: this.addDetailInfo.details
      })
      if (res.data.success) {
        this.$Message.success('保存成功！')
        this.addModalShow = false
        this.getPlanList()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
        this.addModalShow = true
      }
    },
    // 计算个人缴纳金额
    async totalMoneyEmployee (data) {
      let res = await systemApi.getTotalAmount({
        Money: data.employee.baseAmount,
        Precision: data.precision,
        Percent: data.employee.percent
      })
      data.employee.totalAmount = res.data.data
    },
    // 计算单位缴纳金额
    async totalMoneyCompany (data) {
      let res = await systemApi.getTotalAmount({
        Money: data.company.baseAmount,
        Precision: data.precision,
        Percent: data.company.percent
      })
      data.company.totalAmount = res.data.data
    },
    totalMoney (data) {
      this.totalMoneyEmployee(data)
      this.totalMoneyCompany(data)
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getPlanList()
    },
    // 分页
    pageChangeFn (index) {
      this.PageIndex = index
      this.getPlanList()
    },
    // table选择
    tableSelectChange (value) {
      this.idList = value.map((item) => {
        return item.id
      })
    },

    // 删除按钮
    cancelFn () {
      if (this.idList.length > 0) {
        this.$Modal.confirm({
          title: '确定删除？',
          content: '<p>确认后公积金方案将被删除！</p>',
          onOk: () => {
            this.deletePlan()
          },
          onCancel: () => {

          }
        })
      } else {
        this.$Message.warning('请先选择需要删除的方案！')
      }
    },
    addFn () {
      this.getAddModalInfo()
      this.addModalShow = true
    },
    // 全部补缴
    bjAllFn (value) {
      if (value) {

      } else {

      }
    },
    // 查看按钮
    checkInfoFn (id) {
      this.detail_id = id
      this.checkModalTitle = '公积金参数查看'
      this.isCheckModel = true
      this.checkModalShow = true
      this.getPlanDetail()
    },
    // 列表修改按钮
    getReviseAfInfo (id) {
      this.detail_id = id
      this.isCheckModel = false
      this.checkModalTitle = '公积金参数修改'
      this.checkModalShow = true
      this.getPlanDetail()
    },

    // 查看弹窗中的关闭
    closeCheckModal () {
      this.checkModalShow = false
    },
    // 查看弹窗中的修改按钮
    reviseFromModal () {
      this.checkModalTitle = '公积金方案修改'
      this.isCheckModel = false
    },
    // 查看修改弹窗中的确认修改按钮
    confirmRevise () {
      this.saveRevise()
    },
    // 新增弹窗中的确定
    confirmFn () {
      this.addSave()
    },
    // 增员起止时间校验
    increasDayVerification (data) {
      if (data.increasDay.end < data.increasDay.begin) {
        this.$Message.warning('截止时间不能早于开始时间！！')
        data.increasDay.end = data.increasDay.begin
      }
    },
    // 减员起止时间校验
    reduceDayVerification (data) {
      if (data.reduceDay.end < data.reduceDay.begin) {
        this.$Message.warning('截止时间不能早于开始时间！！')
        data.reduceDay.end = data.reduceDay.begin
      }
    }
  }
}
</script>
<style lang="less">
  .af-add-modal-lzw{
    .ivu-modal-wrap{
      top:20%;
      bottom: 20%;
      left: 20%;
      right: 20%;
    }
    .ivu-input[disabled]{
      color: #333;
    }
    .ivu-select-input[disabled]{
      color: #333;
      -webkit-text-fill-color: #333;
    }
    .ivu-checkbox-disabled.ivu-checkbox-checked .ivu-checkbox-inner:after{
      border-color: #333;
    }
    .ivu-select-disabled .ivu-select-selection{
      color: #333;
    }
    .ivu-divider, .ivu-divider-vertical{
      z-index: 99;
    }
  }
</style>
<style lang="less" scoped>
  .search-form-lzw{
    .ivu-col{
      display: flex;
      align-items: center;
      span.label-txt{
        vertical-align: middle;
        float: left;
        min-width: 80px;
        font-size: 12px;
        color: #515a6e;
        line-height: 1;
        padding: 10px 12px 10px 0;
        box-sizing: border-box;
      }
      .ivu-select{
        flex: 1;
      }
      .ivu-input-wrapper{
        flex: 1;
      }
    }
  }
</style>
